package com.kdtech.analyse.Bbs;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.DoMainUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.NumberUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import sun.org.mozilla.javascript.internal.NativeObject;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.DoMainUtils;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;

/**
 * 奥一论坛
 * @author Persh
 *
 * 2014-11-18
 */
public class OeeeeBbsAnalyse implements AnalyseNews {

	
	public boolean isDetailPage(String url) {
		String[] regex = {
				"http://bbs.oeeee.com/thread-[0-9]*-1-1.html",
				"http://baoliao.oeeee.com/index/show/id/[0-9]*.html"
		};
		return RegexUtils.matchAny(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta bbs = new NewsMeta();
		String htmltxt = urlMeta.getHtml();
		if(htmltxt!=null && htmltxt.toLowerCase().startsWith("﻿<script")){
			String newAddr = getNewAddr(urlMeta.getUrl(),htmltxt);
			urlMeta = CrawlHTML.responseToURL(newAddr);
			htmltxt = urlMeta.getHtml();
		}
		String url = urlMeta.getUrl();

		bbs.setUrl(url);
		String title = null;
		String content = null;
		Long date = null;
		Integer commnetNum = null;
		Integer clickNum = null;
		String author = null;

		Document doc = Jsoup.parse(htmltxt);

		title = doc.select("h1.ts").text();
		if(StringUtils.isBlank(title)){
			title = doc.select("h1").text();
		}
		Element firstDiv = doc.select("div#postlist > div[id^=post_]").first();
		if(firstDiv!=null){
			author = firstDiv.select("div.authi a.xw1").text();
			content = HtmlCleaner.getContentHtml(url,  firstDiv.select("td.t_f"));
			date = DateUtils.matchDate(firstDiv.select("div.authi span[title]").attr("title"));
		}
		if(StringUtils.isBlank(author)){
			author = doc.select("div.main-des span.blue").text();
		}
		if(date==null){
			date = DateUtils.matchDate(doc.select("div.main-des").text());
		}
		if(StringUtils.isBlank(content)){
			content = HtmlCleaner.getContentHtml(url,  doc.select("div.main-content"));
		}
		String commTxt ="";
		if (clickNum == null && commnetNum==null ){
			commTxt = doc.select("div.hm").text();
			clickNum = NumberUtils.matchNumber(StringUtils.substringBefore(commTxt, "|"));
			commnetNum = NumberUtils.matchNumber(StringUtils.substringAfter(commTxt, "|"));
		}

		if (clickNum == null && commnetNum==null ){
			commTxt = doc.select("div.main-des").text();
			clickNum = NumberUtils.matchNumber(StringUtils.substringBetween(commTxt, "阅读数", "评论数"));
			commnetNum = NumberUtils.matchNumber(StringUtils.substringAfter(commTxt, "评论数"));
		}
		bbs.setTitle(title);
		bbs.setContent(content);
		bbs.setDate(date);
		/**
		 * 解析用于更新的地址
		 */
		bbs.setUpdateUrl(url);
		bbs.setClickNum(clickNum);
		bbs.setCommentNum(commnetNum);
		bbs.setAuthor(author);
		return bbs;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		if(meta!=null){
			String updateUrl = meta.getUpdateUrl();
			if (StringUtils.isNotBlank(updateUrl)){
				UrlMeta urlMeta = CrawlHTML.responseToURL(updateUrl);
				return parserHtml(urlMeta);
			}
			return null;
		}
		return null;
	}

	public static void main(String[] args) {
		OeeeeBbsAnalyse a = new OeeeeBbsAnalyse();

		String url = "http://baoliao.oeeee.com/index/personal/userid/313294.html";
		System.out.println(DoMainUtils.GetDomainName(url));
		if (!a.isDetailPage(url)) {
			System.out.println("不匹配规则");
		} else {
			UrlMeta meta = CrawlHTML.responseToURL(url);
			NewsMeta parserHtml = a.parserHtml(meta);
			System.out.println(parserHtml);
		}
	}
	

	public static String getNewAddr(String url,String jsData){
		jsData = jsData.replace("﻿<script type=\"text/javascript\">", "").replace("</script>", "");
		    String oldJsData=jsData;
		try {
			 jsData = "var returl = '';var window = {};var location = {href:'',replace:function(o){returl= o;},assign:function(o){returl= o;}};\r\n" + jsData;
			 jsData = jsData.replace("function getName()","function getName(caller)");
			 jsData = jsData.replace("var caller=getName.caller;", "");
			 jsData = jsData.replace("getName()", "getName(arguments.callee)");

			 jsData =  jsData.replaceAll("\\s+\\(","(");
				jsData =  jsData.replaceAll("\\s+\\=","=");
				 jsData = "var returl = '';var window = {};var location = {href:'',replace:function(o){returl= o;},assign:function(o){returl= o;}};" + jsData;
				 jsData = jsData.replace("function getName()","function getName(caller)");
				 jsData = jsData.replace(
						 "var caller=getName.caller;", "");
				 jsData = jsData.replace("getName()", "getName(arguments.callee)");
				 jsData = replaceChar(jsData,"in");
				 jsData = replaceChar(jsData,"if");
				 jsData = replaceChar(jsData,"do");
//			 Map<String,String> replaceMap = new HashMap<String,String>();
//			 replaceMap.put("in\\s()","testin");
//			 replaceMap.put("in\\s=","testin");
//			 replaceMap.put("if\\s()","testif");
//			 replaceMap.put("if\\s=","testif");
//
//			 Iterator<Entry<String, String>> iterator = replaceMap.entrySet().iterator();
//			 while(iterator.hasNext()){
//				 Entry<String, String> next = iterator.next();
//				 String key = next.getKey();
//				 String value = next.getValue();
//				 Pattern pattern = Pattern.compile(key);
//				 Matcher matcher = pattern.matcher(jsData);
//				 while(matcher.find()){
//					 System.out.println("replace->"+matcher.group(0));
//					 jsData = jsData.replace(matcher.group(0),value);
//				 }
//			 }
			  ScriptEngineManager manager = new ScriptEngineManager();
			  ScriptEngine engine = manager.getEngineByName("javascript");
			  engine.eval(jsData);
			  Object returl =  engine.get("returl");
		if(returl!=null && !returl.toString().equals("")){
			  }else{
				  Object obj = engine.get("location");
				if (obj instanceof NativeObject){
					  NativeObject object = (NativeObject) obj;
					  returl = object.get("href");
				  }else{
					  returl = obj;
				  }
			  }
			  String substringAfter = StringUtils.substringAfter(returl.toString(), "?");
			  return url+"?"+substringAfter;

		} catch (ScriptException e) {
			System.err.println(url);
			System.err.println(oldJsData);
			System.err.println(jsData);
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	private static String replaceChar(String jsData, String string) {
		jsData = jsData.replace("}"+string+"=function(", "}f_"+string+"=function(");
		jsData = jsData.replace(";"+string+"=function(", ";f_"+string+"=function(");
		 jsData = jsData.replace("function "+string+"(", "function f_"+string+"(");
		 jsData = jsData.replace(" "+string+"(", " f_"+string+"(");
		 jsData = jsData.replace("+"+string+"(", "+f_"+string+"(");
		 jsData = jsData.replace(" "+string+"=", " f_"+string+"=");
		 jsData = jsData.replace(";"+string+"=", ";f_"+string+"=");
		 jsData = jsData.replace("+"+string+"=", "+f_"+string+"=");
		 jsData = jsData.replace("}"+string+"=", "}f_"+string+"=");
		 jsData = jsData.replace("+"+string+"+", "+f_"+string+"+");
		 jsData = jsData.replace("+"+string+";", "+f_"+string+";");
		return jsData;
	}
}
